package com.winchain.chainbill.tbill.biz.controller;

import com.shell.bee.acct.account.po.AcctBas;
import com.shell.bee.acct.account.po.AcctBkp;
import com.shell.bee.base.annotation.Logging;
import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.entity.mvc.RetMsg;
import com.shell.bee.file.service.PubFileUploadService;
import com.shell.bee.file.vo.FileWapper;
import com.shell.bee.invoince.po.InvDfr;
import com.shell.bee.invoince.service.InvDfrService;
import com.shell.bee.ocr.api.OcrApi;
import com.shell.bee.ocr.tbill.OcrTBillReq;
import com.shell.bee.ocr.tbill.OcrTBillRes;
import com.shell.bee.persistence.model.PageLimit;
import com.shell.constant.rel.AssetCode;
import com.shell.customer.feign.CustomerTagFeign;
import com.shell.framework.utils.CommonDataUtil;
import com.winchain.chainbill.basic.charge.service.ValComService;
import com.winchain.chainbill.basic.charge.vo.ValComVo;
import com.winchain.chainbill.basic.cus.po.CusRec;
import com.winchain.chainbill.basic.cus.service.CusGrpService;
import com.winchain.chainbill.basic.cus.service.CusRecService;
import com.winchain.chainbill.bill.base.po.CbDctOverdue;
import com.winchain.chainbill.bill.base.po.CbDctRpmt;
import com.winchain.chainbill.bill.base.service.CbAttService;
import com.winchain.chainbill.bill.base.service.CbDctOverdueService;
import com.winchain.chainbill.bill.base.service.CbDctRpmtService;
import com.winchain.chainbill.repayment.vo.CbDctRpmtVo;
import com.winchain.chainbill.risk.utill.RateUtil;
import com.winchain.chainbill.tbill.biz.service.TBillService;
import com.winchain.chainbill.tbill.biz.vo.TBillQueryVo;
import com.winchain.chainbill.tbill.biz.vo.TbRecVo;
import com.winchain.chainbill.trade.service.BillAcctBlcService;
import com.winchain.chainbill.trade.service.BillAcctService;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TBillController {
	@Autowired
	private TBillService tBillService;
	@Autowired
	private BillAcctService billAcctService;
	@Autowired
	private CbAttService cbAttService;
	@Autowired
	private ValComService valComService;
	@Autowired
	private CusGrpService cusGrpService;
	@Autowired
	private BillAcctBlcService billAcctBlcService;
	@Autowired
	private CustomerTagFeign customerTagFeign;
	@Autowired
	private InvDfrService invDfrService;
	@Autowired
	private CusRecService cusRecService;
	@Autowired
	private CbDctOverdueService cbDctOverdueService;
	@Autowired
	private CbDctRpmtService cbDctRpmtService;
	@Resource(name = "${file.updownload.service}")
	private PubFileUploadService pubFileUploadService;

	@RequestMapping
	@ResponseBody
	@Logging(module = "��������", methods = "��������")
	public List<TbRecVo> queryTBills(PageLimit limit, TBillQueryVo tBillQueryVo) {
		return this.tBillService.queryTBills(limit, tBillQueryVo);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "商品管理", methods = "获取初始化参数")
	public Map<String, Object> getInitData() {
		Map<String, Object> ret = new HashMap<String, Object>();
		String cusId = CommonDataUtil.getCurEntId();
		String cusName = CommonDataUtil.getCurEntName();
		AcctBas acct = this.billAcctService.getAcctBas(cusId, null, "00");
		ret.put("cusId", cusId);
		ret.put("cusName", cusName);
		ret.put("acct", acct);
		return ret;
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "��������", methods = "��������")
	public RetMsg saveTBill(TbRecVo tbRecVo) {
		return this.tBillService.saveTBill(tbRecVo);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "商票管理", methods = "立即贴现")
	public RetMsg dctImmediately(TbRecVo tbRecVo) {
		return this.tBillService.dctImmediately(tbRecVo);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "��������", methods = "����")
	public RetMsg dct(TbRecVo tbRecVo) {
		return this.tBillService.dct(tbRecVo, false);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "��������", methods = "��������")
	public TbRecVo detail(String billId) {
		TbRecVo tbRecVo = this.tBillService.getDetail(billId);
		this.cbAttService.setTbAtt(tbRecVo);
		if (StringUtil.notEmpty(tbRecVo.getDctId())) {
			InvDfr invDfr = this.invDfrService.selectByBiz(tbRecVo.getDctId(), "2");
			if ((invDfr != null) && (!"1".equals(invDfr.getState()))) {
				tbRecVo.setShowInvoice(false);
			}
			CbDctRpmt dctRpmt = this.cbDctRpmtService.selectDctRpmtByBizIdAndType(tbRecVo.getDctId(), "2");
			if (dctRpmt != null) {
				tbRecVo.setRpmtDate(dctRpmt.getRpmtDate());
				tbRecVo.setCapital(dctRpmt.getCapital());
				tbRecVo.setRpmtType(dctRpmt.getRpmtType());
				tbRecVo.setRpmtState(dctRpmt.getRpmtState());
				tbRecVo.setRpmtInt(dctRpmt.getRpmtInt());
			}
			CbDctOverdue dctOverdue = this.cbDctOverdueService.selectDctOverdueByBizIdAndType(tbRecVo.getDctId(), "2");
			if (dctOverdue != null) {
				tbRecVo.setOvdId(dctOverdue.getOvdId());
				tbRecVo.setOvdInt(dctOverdue.getOvdInt());
			}
		}
		return tbRecVo;
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "��������", methods = "��������")
	public List<TbRecVo> queryTBillsForMgt(PageLimit limit, TBillQueryVo tBillQueryVo) {
		return this.tBillService.queryTBillsForMgt(limit, tBillQueryVo);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "��������", methods = "��������")
	public RetMsg confirmReceivePayment(String billId, CbDctRpmtVo dctRpmtVo) {
		this.tBillService.confirmReceivePayment(billId, dctRpmtVo);
		return new RetMsg("success", false, "������������");
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "��������", methods = "��������������")
	public List<TbRecVo> selectUnuploadInvoiceListByPage(PageLimit limit, TBillQueryVo tBillQueryVo) {
		return this.tBillService.selectUnuploadInvoiceListByPage(limit, tBillQueryVo);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "��������", methods = "������������")
	public RetMsg uploadInvoices(String dctId, String attInvoicesJson) throws Exception {
		if ((StringUtil.emptyAndNull(dctId)) || (StringUtil.emptyAndNull(attInvoicesJson))) {
			return new RetMsg("error", true, "����������");
		}
		this.tBillService.uploadInvoices(dctId, attInvoicesJson);
		return new RetMsg("success", false, "��������������");
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "商票管理", methods = "票据号码唯一性校验")
	public boolean existBillCode(String billId, String billCode) {
		return this.tBillService.existBillCode(billId, billCode);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "��������", methods = "OCR����������")
	public Map<String, Object> resolveTBill(@RequestParam(value = "fileId", required = false) String fileId)
			throws Exception {
		FileWapper fileWapper = this.pubFileUploadService.getDownloadFile(fileId);
		OcrTBillReq req = new OcrTBillReq();
		req.setImagePath(fileWapper.getFile().getPath());
		OcrTBillRes res = OcrApi.valTBill(req);
		Map<String, Object> ret = new HashMap();
		ret.put("tbill", res);
		ret.put("buyers", getBuyerMaps(res.getBuyerNm()));
		return ret;
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "商票管理", methods = "查询出票人信息")
	public List<Map<String, Object>> findBuyerInfo(String searchValue) throws Exception {
		return getBuyerMaps(searchValue);
	}

	private List<Map<String, Object>> getBuyerMaps(String buyerNm) {
		List<CusRec> cusRecs = this.cusRecService.selectListByName(buyerNm);
		List<Map<String, Object>> buyerMaps = new ArrayList<Map<String, Object>>();
		for (CusRec cusRec : cusRecs) {
			AcctBas acct = this.billAcctService.getAcctBas(cusRec.getCusId(), null, "00");
			String grpId = cusRec.getGrpId();
			if (!StringUtil.emptyAndNull(grpId)) {
				List<CusRec> finners = this.cusGrpService.findGroupEnts(grpId, "FIN_BUYER");
				CusRec finner = (CusRec) finners.get(0);
				AcctBkp bkp = this.billAcctBlcService.getCreditAcctBkpByCont(finner.getFinId(), cusRec.getCusId(),
						AssetCode.XTB.name(), "41");
				if ((bkp != null) && ("1".equals(bkp.getQuotaState()))) {
					Map<String, Object> focalMap = new HashMap();
					focalMap.put("buyerId", cusRec.getCusId());
					focalMap.put("buyerNm", cusRec.getCusName());
					focalMap.put("buyerAcct", acct);

					ValComVo serviceFee = this.valComService.getTbValComVo(finner.getCusId(), grpId);
					if (serviceFee != null) {
						focalMap.put("serFeeRate", serviceFee.getValStd());
						focalMap.put("serFeeMin", serviceFee.getValMin());
						focalMap.put("serFeeMax", serviceFee.getValMax());
					}
					focalMap.put("finId", finner.getCusId());
					focalMap.put("finNm", finner.getCusName());

					String dctFixedRate = RateUtil.getFixedRate(grpId, finner.getCusId(), "tb_dct_fixed_rate");
					if (StringUtil.emptyAndNull(dctFixedRate)) {
						throw new UnCheckMsgException("������������������������������");
					}
					focalMap.put("fixedRate", dctFixedRate);
					focalMap.put("dctQt", bkp.getAcctBlc().subtract(bkp.getAcctBlk()));

					String ivUploadLimitDay = RateUtil.getInvoiceUploadLimitDays(grpId, grpId, cusRec.getCusId(),
							"iv_upload_limit_day");

					String ivUploadGracePeriod = RateUtil.getInvoiceUploadGracePeriod(grpId, grpId, cusRec.getCusId(),
							"iv_upload_grace_period");
					focalMap.put("ivUploadLimitDay", ivUploadLimitDay);
					focalMap.put("ivUploadGracePeriod", ivUploadGracePeriod);
					buyerMaps.add(focalMap);
				}
			}
		}
		return buyerMaps;
	}
}
